<?php
$this->headTitle()->prepend($this->translate('about_product_description') .' - ');
$this->headLink()->appendStylesheet($this->APP_STATIC_SERVER . '/skins/admin/default/css/form.css')
                ->appendStylesheet($this->APP_STATIC_SERVER . '/skins/admin/default/css/filelist.css');
$this->headScript()
        ->appendFile($this->APP_STATIC_SERVER . '/js/jquery.validate.js')
        ->appendFile($this->APP_STATIC_SERVER . '/js/tomato.util.js')
        ->appendFile($this->APP_STATIC_SERVER . '/js/tinymce/tiny_mce.js')
        ->appendFile($this->APP_STATIC_SERVER . '/js/jquery.json-2.3.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/js/jquery.base64.min.js');
?>

<div id="r-heading">
    <img src="<?php echo $this->APP_STATIC_SERVER . '/skins/admin/default/images/product.png'; ?>" alt=""/>
    <span><?php echo $this->translate('task_edit_product')?></span>
</div>
<?php
$message = $this->flashMessenger();
if($message){?>
    <div id="message"><ul><?php echo $message; ?></ul></div>
<?php }?>
<form id="frmAddProduct" class="" enctype="application/x-www-form-urlencoded" action="" method="post">
    <div class="r-left" style="width:60%; float:left;">
        <div class="row">
            <label for="language"><?php echo $this->translate('product_language'); ?></label>
            <?php echo $this->languageSelector(array('name' => 'language', 'selected' => $this->product->language)); ?>
        </div>
        <div class="row">
            <label><?php echo $this->translate('product_source_item'); ?></label>
            <div class="translatable translationSourceItems">
            <?php
            echo $this->translatableProduct(array(
                                    'id'       => 'sourceItem',
                                    'name'     => 'sourceItem',
                                    'class'     => '',
                                    'selected' => (null == $this->sourceProduct) ? null : $this->sourceProduct->id,
                                    'disabled' => null,
                              ), $this->product->language);
            ?>
            </div>
        </div>
        <div class="row">
            <label for="name" class="required"><?php echo $this->translate('product_name')?></label>
            <input class="text" type="text" name="name" id="name" value="<?php echo $this->product->name ?>" size="50" />
        </div>
        <div class="row">
            <label for="slug" class="required"><?php echo $this->translate('product_slug'); ?></label>
            <input type="text" name="slug" id="slug" value="<?php echo $this->product->slug ?>" size="50" />
        </div>
        <div class="row">
            <label for="price"><?php echo $this->translate('product_price'); ?></label>
            <input type="text" name="price" id="price" value="<?php echo $this->product->price ?>" size="30" />
        </div>
        <div class="row">
            <label for="demo_url"><?php echo $this->translate('demo_url'); ?></label>
            <input type="text" name="demo_url" id="demo_url" value="<?php echo $this->product->demo_url ?>" size="50" />
        </div>
        <div class="row">
            <label for="description"><?php echo $this->translate('product_description')?></label>
            <textarea style="width:323px;" name="description" rows="24" cols="100"><?php echo $this->product->description ?></textarea>
        </div>
        <div class="row">
            <label for="specification" class="required"><?php echo $this->translate('product_specification')?></label>
            <textarea name="specification" class="tinymce" id="specification" rows="24" cols="100"><?php echo $this->product->specification ?></textarea>
        </div>
    </div>
    <div class="r-right" style="width:35%;float:right;">
        <div class="box">
            <div class="b-title">
                <?php echo $this->translate('product_published')?>
            </div>
            <div class="b-container">
                <div class="row">
                    <label><?php echo $this->translate('product_category')?></label>
                    <div class="translatable">
                        <?php echo $this->helperLoader('category')->categorySelect(
                                                                        array('id' => 'category', 'name' => 'category_id', 'selected' => $this->product->category_id),
                                                                        $this->product->language, 'product'); ?>
                    </div>
                </div>
                <div class="row">
                    <label><?php echo $this->translate('product_status')?></label>
                    <select name="status">
                        <option value="inactived" <?php echo (($this->product->status == 'inactived') ? 'selected="selected"' : '')?>><?php echo $this->translate('product_list_filter_inactived')?></option>
                        <option value="actived" <?php echo (($this->product->status == 'actived') ? 'selected="selected"' : '')?>><?php echo $this->translate('product_list_filter_actived')?></option>
                        <option value="drafted" <?php echo (($this->product->status == 'drafted') ? 'selected="selected"' : '')?>><?php echo $this->translate('product_list_filter_drafted')?></option>
                        <option value="deleted" <?php echo (($this->product->status == 'deleted') ? 'selected="selected"' : '')?>><?php echo $this->translate('product_list_filter_deleted')?></option>
                    </select>
                </div>
                <div class="row">
                    <label style="float: left; width: 220px;"><?php echo $this->translate('product_allow_comment')?></label>
                    <input type="checkbox" name="allow_comment" value="1" <?php echo (($this->product->allow_comment) ? 'checked="checked"' : '')?>/>
                </div>
                <div class="row">
                    <label style="float: left; width: 220px;"><?php echo $this->translate('product_featured')?></label>
                    <input type="checkbox" name="featured" value="1" <?php echo (($this->product->featured) ? 'checked="checked"' : '')?>/>
                </div>
                <div class="row">
                    <label for="author"><?php echo $this->translate('product_author')?></label>
                    <input type="text" name="author" id="author" value="<?php echo $this->product->author?>" size="50" />
                </div>
            </div>
        </div>
        <div class="box">
            <div class = "b-title">
                <?php echo $this->translate('product_multimedia')?>
            </div>
            <div class="b-container">
                <?php
                echo
                $this->helperLoader('upload')->uploader('product',
                        array('extension' => '*.jpg;*.jpeg;*.png;*.gif', 'fileExt' => '*.jpg;*.jpeg;*.png;*.gif', 'multi' => true, 'auto' => true, 'simUploadLimit' => 5, 'sizeLimit' => 1024 * 1024 * 5),
                        array('onComplete' => 'onUploadComplete','onError' => 'onUploadError'));
                ?>
                <div style="margin-top: 10px;" class="photos"><ul id="photos"></ul></div>
            </div>
        </div>
        <div class="box">
            <div class = "b-title">
                <?php echo $this->translate('product_thumbnail')?>
            </div>
             <div class="b-container">
                <input type ="hidden" value='<?php echo $this->productImages ?>' name="productImages" id="productImages"/>
                <p><?php echo $this->translate('product_select_image_guide'); ?></p>
                <img src="<?php echo $this->product->image_thumbnail?>" alt="" id="image-thumbnail"/>
            </div>
        </div>
        <div class="box">
            <div class = "b-title">
                <?php echo $this->translate('product_attachment'); ?>
            </div>
            <div class="b-container">
                <?php
                echo
                $this->helperLoader('upload')->uploader('product',
                        array('extension' => '*.zip;*.rar;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx', 'fileExt' => '*.zip;*.rar;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx', 'multi' => true, 'auto' => true, 'simUploadLimit' => 5, 'sizeLimit' => 1024 * 1024 * 30),
                        array('onComplete' => 'onUploadAttachmentComplete','onError' => 'onUploadError'));
                ?>
                <div style="margin-top: 10px;" id="attachments"><ul></ul></div>
                <input type="hidden" name="attachment" value="<?php echo $this->product->attachment?>" id="attachment"/>
            </div>
        </div>
        <div class="box">
            <div class="b-title"><?php echo $this->translate('product_seo'); ?></div>
            <div class="b-container">
                <div class="row">
            <label for="meta_title"><?php echo $this->translate('product_meta_title'); ?></label>
            <input type="text" name="meta_title" id="meta_title" value="<?php echo $this->product->meta_title?>" size="50" />
        </div>
        <div class="row">
            <label for="meta_description"><?php echo $this->translate('product_meta_description'); ?></label>
            <textarea cols="100" rows="25" name="meta_description" id="meta_description"><?php echo $this->product->meta_description?></textarea>
        </div>
        <div class="row">
            <label for="meta_keywords"><?php echo $this->translate('product_meta_keywords'); ?></label>
            <input type="text" name="meta_keywords" id="meta_keywords" value="<?php echo $this->product->meta_keywords?>" size="50" />
        </div>

            </div>
        </div>
        <div class="row" style="width:100%; clear: both;">
            <input class="button" type="submit" name="submit" id="submit" value="<?php echo $this->translate('common_save'); ?>" />
            <input class="button" type="reset" name="reset" id="reset" value="<?php echo $this->translate('common_reset'); ?>" />
        </div>
    </div>
</form>
<script type="text/javascript">
    $(document).ready(function(){
        //create attachment list
        if($('#attachment').val() != ''){
            var attachments = $.evalJSON($.base64.decode($('#attachment').val()));
            for(var i = 0; i< attachments.length; i++){
                $('#attachments ul').append(
                    '<li id="attachment-' + attachments[i].id + '" class="' + attachments[i].type + '">'
                    + attachments[i].name
                    + '<span><a class="a_helper_action_delete" href="" onclick="removeAttachment(' + attachments[i].id + '); return false;"></a></span>'
                    +'</li>'

                );
            }
        }
        /**
         * Validate form
         */
        $.validator.addMethod('slug', function(value) {
            var regex = new RegExp(/^[a-z0-9\-]+$/);
            if (value.match(regex)) {
                return true;
            } else {
                return false;
            }
        });
//        $.validator.addMethod('value', function(value){
//            return value != 0;
//        });

        $('#frmAddProduct').validate({
            rules: {
                name: {
                    required: true,
                    maxlength: 255
                },
                slug: {
                    required: true,
                    slug: true,
                    maxlength: 255
                }
            },
            messages: {
                name: {
                    required: "<?php echo $this->translate('product_name_required'); ?>",
                    maxlength: "<?php echo $this->translate('product_name_maxlength'); ?>"
                },
                slug: {
                    required: "<?php echo $this->translate('product_slug_required'); ?>",
                    slug: "<?php echo $this->translate('product_slug_validate'); ?>",
                    maxlength: "<?php echo $this->translate('product_slug_maxlength'); ?>"
                }

            }
        });


        //điền slug
        $("#name").change(function(){
            $('#slug').val(Tomato.Util.generateSlug($(this).val()));
        });
        /**
         * Init TinyMCE instances
         */
        tinyMCE.init({
            theme: 'advanced',
            theme_advanced_toolbar_location: 'top',
            theme_advanced_toolbar_align: 'left',
            width: '600',
            height: '225',
            mode: 'exact',
            elements: 'description',
            relative_urls: false,
            remove_script_host: false
        });

        tinyMCE.init({
            theme: 'advanced',
            plugins: 'safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,preelementfix',
            theme_advanced_buttons2: 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo',
            theme_advanced_buttons3: 'link,unlink,anchor,image,cleanup,code,|,preview,|,forecolor,backcolor',
            theme_advanced_buttons4: 'tablecontrols,ltr,rtl,', //"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_toolbar_location: 'top',
            theme_advanced_toolbar_align: 'left',
            width: '600',
            height: '400',
            mode: 'exact',
            elements: 'specification',
            relative_urls: false,
            remove_script_host: false,
            onchange_callback: function(editor) {
                tinyMCE.triggerSave();
                $('#' + editor.id).valid();
            }
        });
});
   /**
 * Upload handlers
 */
function onUploadError(event,ID,fileObj,errorObj) {
      alert(errorObj.type + ' Error: ' + errorObj.info);
    }
function onUploadComplete(event, ID, fileObj, response, data) {
    var images = jQuery.parseJSON(response);
    var presentImage = $('<img/>');
    $(presentImage).attr('src', images.thumbnail.url)
    .attr('width', '100').attr('height', '100')
    .attr('style', 'cursor: pointer')
    .click(function() {
        selectImage(images);
    });
    var select = $('<select/>');
    $(select).attr('width', '100');
    $('<option/>').attr('value', '').html('---').appendTo(select);

    for (var thumb in images) {
        $('<option/>').attr('value', images[thumb].url).html(images[thumb].size).appendTo(select);
    }
    $(select).change(function() {
        if ($(this).val() != '') {
            insertImage($(this).val());
        }
    });

    $('<li/>').append(presentImage).append($('<br/>')).append(select).appendTo($('#photos'));
};
function selectImage(images) {
    var urls = {};
    for (var thumb in images) {
        urls[thumb] = images[thumb].url;
    }
    $('#productImages').val($.toJSON(urls));
    $('#image-thumbnail').attr('src',images.thumbnail.url);
};
//for upload attachment
function onUploadAttachmentComplete(event, ID, fileObj, response, data) {
    var result = $.evalJSON(response);
    if(result.status){

        $('#attachments ul').append(
            '<li id="attachment-' + result.file.id + '" class="' + result.file.type + '">'
                + result.file.name
                + '<span><a class="a_helper_action_delete" href="" onclick="removeAttachment(' + result.file.id + '); return false;"></a></span>'
                +'</li>'

        );
        var attachments = new Array();
        if($('#attachment').val() != ''){
            attachments = $.evalJSON($.base64.decode($('#attachment').val()));
        }    
        attachments.push({id: result.file.id, name: result.file.name, url: result.file.url, type: result.file.type});
        $('#attachment').val($.base64.encode($.toJSON(attachments)));
    }
}
function removeAttachment(id){
        $.ajax({
            url: '<?php echo $this->url(array(), 'multimedia_file_delete') ?>',
            data : {id : id},
            type: 'POST',
            success: function(response){
                alert(response);
                var result = $.evalJSON(response);
                if(result.status){
                    var attachments = $.evalJSON($.base64.decode($('#attachment').val()));
                    for(var i = 0; i < attachments.length; i++){
                        if(attachments[i].id == id){
                            attachments.splice(i,1);
                            $("#attachment-" + id).fadeOut('slow');
                        }
                    }
                    $('#attachment').val($.base64.encode($.toJSON(attachments)));

                }
            }
        });
        return false;
    }
/**
 * Insert image to TinyMCE editor at current position
 * @param string url The image url
 */
function insertImage(url) {
    tinyMCE.getInstanceById('specification').execCommand('mceInsertContent', false, '<img src="' + url + '" />');
};
</script>